"ui";

const Api = require("./Api/api");
const Storages = require("./Api/storage");
const Utils = require("./Services/utils");
const content = require("./Assets/alertContent");
const tb = require("./Script/taobao");
const JD = require("./Script/jd");
const tmAlert = require("./Services/timeAlert");
const imgs = require("./Assets/base64Imgs");
const styles = require("./Assets/commonStyle");
const versions = require("./Api/version");
const loadings = require("./component/loading");
const fastShopApis = require("./Api/fastShopApi");

ui.layout(
  <drawer id="drawer">
    <vertical>
      <vertical>
        <appbar>
          <toolbar
            id="toolbar"
            title="小助手"
            bg="{{styles.baseColor}}"
            textColor="#000000"
            paddingTop="2dp"
            h="auto"
          ></toolbar>
          <tabs bg="{{styles.baseColor}}" id="tabs" />
        </appbar>

        <viewpager id="viewpager">
          {/* 淘宝的内容 */}
          <frame>
            <vertical padding="15">
              <horizontal marginBottom="4dp">
                <text>模式选择</text>
                <spinner
                  id="sp1"
                  paddingLeft="15dp"
                  textSize="12sp"
                  textColor="#333333"
                  entries="购物车|bp链接"
                />
              </horizontal>

              {/* 这个显示时间差值 */}
              <text line="3" id="taobaoRequestTimePlus"></text>
              <horizontal>
                <text>抢购时间：</text>
                <input id="taobaoInput" w="*" inputType="datetime" />
              </horizontal>
              <horizontal>
                <text>抢购时长(s)：</text>
                <input id="taobaoInputTimeLength" w="*" inputType="number" />
              </horizontal>
              <horizontal>
                <text>提前时长(ms)：</text>
                <input id="taobaoEarlyTime" w="*" inputType="number" />
              </horizontal>
              <horizontal>
                <text>bp链接：</text>
                <input id="bpLink" w="*" inputType="text" />
              </horizontal>
              <button id="taobaoStartButton" text="开始运行" />

              <card w="*" h="*" margin="5 20 5 4">
                <text padding="10 10 10 5">bp链接获取/测试:</text>
                <vertical padding="10 10 10 0" marginTop="15">
                  <horizontal>
                    <horizontal>
                      <text>商品id:</text>
                      <input id="goodsId" w="60" inputType="number" />
                    </horizontal>
                    <horizontal>
                      <text>规格skuId:</text>
                      <input id="skuId" w="60" inputType="number" />
                    </horizontal>
                    <horizontal>
                      <text>数量:</text>
                      <input id="skuNum" w="30" inputType="number" />
                    </horizontal>
                  </horizontal>
                  <horizontal>
                    <button id="getBpLink" text="获取BP链接" />
                    <button id="bpLinkTest" text="测试" />
                  </horizontal>
                </vertical>
              </card>
            </vertical>
          </frame>
          {/* 京东内容 */}
          <frame>
            <vertical padding="15">
              {/* 这个显示时间差值 */}
              <text line="3" id="jdRequestTimePlus"></text>

              <text paddingTop="15" text="模式选择："></text>
              <radiogroup orientation="horizontal">
                <radio id="detailMode" text="详情页" checked="true" />
                {/* <radio id="shopCartMode" text="购物车" /> */}
              </radiogroup>

              {/* <horizontal>
                <text>抢购时间：</text>
                <input id="jdInput" w="*" inputType="datetime" />
              </horizontal> */}
              <horizontal>
                <text>抢购时长(s)：</text>
                <input id="jdInputTimeLength" w="*" inputType="number" />
              </horizontal>
              {/* <horizontal>
                <text>提前时长(ms)：</text>
                <input id="jdEarlyTime" w="*" inputType="number" />
              </horizontal> */}
              <button id="jdStartButton" text="开始运行" />
            </vertical>
          </frame>
          <frame>
            <text text="第三页内容" textColor="green" textSize="16sp" />
          </frame>
        </viewpager>
      </vertical>
    </vertical>

    <vertical layout_gravity="left" bg="#ffffff" w="280">
      <img
        w="280"
        h="140"
        scaleType="fitXY"
        src="http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg"
      />
      <vertical paddingTop="15" paddingBottom="15">
        {/* 服务 */}
        {/* <text>服务</text> */}
        <list id="serviceList">
          <vertical padding="15" w="280" bg="?selectableItemBackground">
            <horizontal>
              <frame layout_weight="1">
                <img w="22" h="22" src="{{this.icon}}" alt="" />
              </frame>
              <text layout_weight="1" text="{{this.title}}"></text>
              <Switch id="{{this.id}}" layout_weight="4" w="25" h="25" />
            </horizontal>
          </vertical>
        </list>
      </vertical>
      <horizontal w="280" h="10" bg="#f4f3f1"></horizontal>
      <vertical paddingTop="15" paddingBottom="15">
        {/* <text>菜单</text> */}
        <list id="menuChecks">
          <vertical padding="15" w="280">
            <horizontal id="{{this.id}}">
              <frame layout_weight="1">
                <img w="22" h="22" src="{{this.icon}}" alt="" />
              </frame>
              <text layout_weight="1" text="{{this.title}}"></text>
              <frame layout_weight="4" w="25" h="25">
                <text
                  gravity="right"
                  text="{{this.text ? this.text : ''}}"
                ></text>
              </frame>
            </horizontal>
          </vertical>
        </list>
      </vertical>
    </vertical>
  </drawer>
);

//设置滑动页面的标题
ui.viewpager.setTitles(["淘宝", "京东", "苏宁", "123", "qwe", "1ewqe"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

// 服务列表
ui.serviceList.setDataSource([
  {
    title: "开启时间显示",
    icon: imgs.timeImg,
    id: "timeAlert",
  },
  {
    title: "无障碍服务",
    icon: imgs.settingImg,
    id: "autoService",
  },
]);
ui.menuChecks.setDataSource([
  {
    title: "免责声明",
    icon: imgs.statement,
    id: "statement",
  },
  {
    title: "QQ一键加群",
    icon: imgs.qqGroup,
    id: "qqGroup",
  },
  {
    title: "清除缓存",
    icon: imgs.clearCache,
    id: "clearCache",
  },
  {
    title: "检查更新",
    icon: imgs.update,
    id: "checkUpdate",
    text: "v" + app.versionName,
  },
]);

//让工具栏左上角可以打开侧拉菜单
ui.toolbar.setupWithDrawer(ui.drawer);

// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启 android.permission.SYSTEM_ALERT_WINDOW
setTimeout(() => {
  ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
      app.startActivity({
        action: "android.settings.ACCESSIBILITY_SETTINGS",
      });
    }
    if (!checked && auto.service != null) {
      auto.service.disableSelf();
    }
  });

  // 显示时间窗
  ui.timeAlert.on("check", function (checked) {
    if (checked) {
      tmAlert.starts();
    } else {
      tmAlert.window.close();
    }
  });

  // 免责声明
  ui.statement.click(() => {
    alert(content.statement);
  });

  // 清除缓存
  ui.clearCache.click(() => {
    Storages.clear();
    toast("缓存已清除");
    ui.taobaoInputTimeLength.setText("5");
    ui.taobaoEarlyTime.setText("200");
  });

  // QQ一键加群
  ui.qqGroup.click(() => {
    const key = "0nbUR8_SMi9mpe2Q4eRRbBBn_Iecy5oG";
    app.startActivity({
      action: "android.intent.action.VIEW",
      data:
        "mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" +
        key,
    });
  });

  // 检查更新
  ui.checkUpdate.click(() => {
    toast("版本查询中");
    setTimeout(() => {
      if (app.versionName == "4.1.1 Alpha2") {
        toast("当前模式为调试模式，无法查询版本");
        return;
      }
      const heightVersion = versions.getVersion();

      if (heightVersion.state) {
        if (String(app.versionName) == String(heightVersion.version)) {
          toast("当前已经是最高版本");
        } else {
          toast(
            "最新版本: v" + heightVersion.version + "，一键加群获取最新版本",
            10
          );
        }
      } else {
        toast("版本查询失败，一键加群获取最新版本");
      }
    }, 200);
  });
}, 1);

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function () {
  // 此时根据无障碍服务的开启情况，同步开关的状态
  ui.autoService.checked = auto.service != null;
});

/** =============================================开启执行线程=============================================== */
threads.start(function () {
  const nowTime = new Date();

  ui.bpLink.setEnabled(false);

  // 设置缓存值
  setDefaultValue();

  ui.run(function () {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
    // 设置抢购默认时间
    ui.taobaoInput.setText(
      Utils.changeTime(nowTime.Format("yyyy/MM/dd hh:mm:ss"))
    );
    // 获取抢购时长
    ui.taobaoInputTimeLength.setText(
      String(Storages.getTMailSettings().buyTime)
    );
    ui.jdInputTimeLength.setText(String(Storages.getJDSettings().buyTime));
    ui.taobaoEarlyTime.setText(
      String(Storages.getTMailSettings().taobaoEarlyTime)
    );
    ui.timeAlert.setChecked(true);
    // 显示各个延时时长
    setTimeShow();
  });
});

// 淘宝开始运行
ui.taobaoStartButton.click(() => {
  // 这里处理bp链接状态
  if (ui.sp1.getSelectedItemPosition() === 1) {
  }
  // 点击开始就保存缓存了
  Storages.setTMailSettings(
    String(ui.taobaoInputTimeLength.getText()),
    String(ui.taobaoEarlyTime.getText())
  );
  if (!showToastAndDefault("taobao")) {
    return;
  }
  // 禁止输入框输入
  setInputEnabled(false, "taobao");
  if (ui.taobaoStartButton.getText() === "开始运行") {
    ui.taobaoStartButton.setText("停止运行");
    threads.start(function () {
      console.setTitle("小助手");
      console.show();
      // 这里开启淘宝脚本执行功能
      if (ui.sp1.getSelectedItemPosition() === 0) {
        tb.taobaoScript(true);
      } else {
        console.log("bp链接模式");
        // TODO: 这里做BP抢购功能
      }
    });
  } else {
    finishScript("taobao");
  }
});

/** bp链接的UI功能 */
ui.getBpLink.click(() => {
  const goodsId = ui.goodsId.getText();
  const skuId = ui.skuId.getText();
  const skuNum = ui.skuNum.getText();

  if (Number(goodsId) === 0) {
    toast("请输入商品id");
    return;
  }
  if (Number(skuNum) === 0) {
    toast("请输入购买数量");
    return;
  }
  const res = fastShopApis.changeBPLink(
    Number(goodsId),
    Number(skuNum),
    skuId ? Number(skuId) : null
  );

  if (res.state) {
    toast("获取成功");
    ui.bpLink.setText(res.url);
  } else {
    toast("获取失败");
  }
});

// 测试调起
ui.bpLinkTest.click(() => {
  if (Number(ui.bpLink.getText()) === 0) {
    toast("请先获取BP链接再进行测试")
    return;
  }
  tb.bpModeTest(ui.bpLink.getText());
});

/** bp链接的UI功能结束 */

// 京东开始运行
ui.jdStartButton.click(() => {
  // 点击开始就保存缓存了
  Storages.setJDSettings(
    ui.detailMode.checked
      ? "detailMode"
      : ui.shopCartMode.checked
      ? "shopCartMode"
      : "",
    String(ui.jdInputTimeLength.getText())
  );

  if (!showToastAndDefault("jd")) {
    return;
  }
  // 禁止输入框输入
  setInputEnabled(false, "jd");
  if (ui.jdStartButton.getText() === "开始运行") {
    ui.jdStartButton.setText("停止运行");
    threads.start(function () {
      console.show();
      // 这里开启京东脚本执行功能
      JD.jdScript(true, Storages.getJDSettings().mode);
    });
  } else {
    finishScript("jd");
  }
});

// 点击开始时的提示
function showToastAndDefault(type) {
  // 处理权限
  if (!ui.autoService.checked) {
    toast(content.showAuto);
    return false;
  }
  switch (type) {
    case "taobao":
      // 如果淘宝时间差为0，则进行提示
      if (Api.tMailTimePlus === "0") {
        toast(content.onlineError);
      }
      if (!Utils.isCorrectForTimeFormat(ui.taobaoInput.getText())) {
        toast(content.timeFormatError);
        return false;
      }
      break;
    case "jd":
      break;
    default:
      break;
  }

  return true;
}

// 设置平台时间显示
function setTimeShow() {
  // 淘宝，这里做一个定时器，如果次数大于50或者值不是"0"则停止定时器
  let tbTempIntervalTime = 0;
  loadings.showLoading();
  let tbRequestFinish = false;
  let jdRequestFinish = false;
  const tbTempInterval = setInterval(() => {
    tbTempIntervalTime++;
    if (Api.tMailTimePlus !== "0") {
      // 设置设备差值显示
      ui.taobaoRequestTimePlus.setText(
        "当前设备比淘宝时间慢" +
          Api.tMailTimePlus +
          "ms，与淘宝服务器响应时间为" +
          Api.tMailNetWorkDelay +
          "ms"
      );
      clearInterval(tbTempInterval);
      tbRequestFinish = true;
    } else if (tbTempIntervalTime > 100) {
      ui.taobaoRequestTimePlus.setText(content.onlineError);
      loadings.hideLoading();
      clearInterval(tbTempInterval);
      tbRequestFinish = true;
    }
  }, 100);

  // 京东，这里做一个定时器，如果次数大于50或者值不是"0"则停止定时器
  let jdTempIntervalTime = 0;
  const jdTempInterval = setInterval(() => {
    jdTempIntervalTime++;
    // if (Api.jdTimePlus !== "0") {
    //   // 设置设备差值显示
    //   ui.jdRequestTimePlus.setText(
    //     "当前设备比京东时间慢" +
    //       Api.jdTimePlus +
    //       "ms，与京东服务器响应时间为" +
    //       Api.jdNetWorkDelay +
    //       "ms"
    //   );
    //   clearInterval(jdTempInterval);
    //   jdRequestFinish = true;
    // } else if (jdTempIntervalTime > 100) {
    ui.jdRequestTimePlus.setText(content.onlineErrorJD);
    clearInterval(jdTempInterval);
    jdRequestFinish = true;
    // }
  }, 100);

  setInterval(() => {
    if (jdRequestFinish && tbRequestFinish) {
      setTimeout(() => {
        loadings.hideLoading();
      }, 300);
    }
  }, 10);
}

// 设置缓存值
function setDefaultValue() {
  ui.run(function () {
    // 设置入口时的默认值
    ui.taobaoRequestTimePlus.setText(content.readyTimeTMail);
    ui.jdRequestTimePlus.setText(content.readyTimeTMail);
    // 获取京东模式选择
    switch (Storages.getJDSettings().mode) {
      case "detailMode":
        ui.detailMode.setChecked(true);
        break;
      case "shopCartMode":
        ui.shopCartMode.setChecked(true);
        break;
      default:
        break;
    }
  });
}

// 设置输入框是否可输入，只要有一项脚本开始运行，则全部禁止输入
function setInputEnabled(state, type) {
  switch (type) {
    // 类型为淘宝时，其他平台按钮禁用
    case "taobao":
      ui.jdStartButton.setEnabled(state);
      break;
    case "jd":
      ui.taobaoStartButton.setEnabled(state);
    default:
      break;
  }

  ui.detailMode.setEnabled(state);

  // ui.shopCartMode.setEnabled(state);
  ui.taobaoInput.setEnabled(state);
  ui.taobaoInputTimeLength.setEnabled(state);
  ui.jdInputTimeLength.setEnabled(state);
  ui.taobaoEarlyTime.setEnabled(state);
  // 这里是转链的按钮和输入框
  ui.goodsId.setEnabled(state);
  ui.skuId.setEnabled(state);
  ui.skuNum.setEnabled(state);
  ui.getBpLink.setEnabled(state);
  ui.bpLinkTest.setEnabled(state);
}

// 结束运行
function finishScript(type) {
  ui.taobaoStartButton.setText("开始运行");
  ui.jdStartButton.setText("开始运行");
  threads.shutDownAll();
  // 开启输入内容
  switch (type) {
    case "taobao":
      setInputEnabled(true, "taobao");
      break;
    case "jd":
      setInputEnabled(true, "jd");
      break;
    default:
      break;
  }

  // 这里关闭所有线程，重启倒计时线程
  tmAlert.window.close();
  tmAlert.starts();
}
